package demo2;

import java.util.PriorityQueue;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-07-29
 * Time: 9:01
 */

class MytimerTask implements Comparable<MytimerTask>{
    private long time;
    private Runnable runnable;

    public MytimerTask(Runnable runnable, long delay){
        this.runnable = runnable;
        time = delay + System.currentTimeMillis();
    }

    public long getTime() {
        return time;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    @Override
    public int compareTo(MytimerTask o) {
        return (int) (this.time - o.time);
    }
}

class Mytimer2{
    PriorityQueue<MytimerTask> priorityQueue = new PriorityQueue<>();


    public void schedule(Runnable runnable, long delay) {
        synchronized (this) {
            MytimerTask mytimerTask = new MytimerTask(runnable, delay);
            priorityQueue.offer(mytimerTask);
            notify();
        }
    }

    public Mytimer2(){
       Thread thread = new Thread(() -> {
           while (true){
               synchronized (this){
                   try {
                       while (priorityQueue.isEmpty()){
                           this.wait();
                       }
                       MytimerTask task = priorityQueue.peek();
                       long curtime = System.currentTimeMillis();
                       long time = task.getTime();
                       if (time <= curtime){
                           priorityQueue.poll();
                           task.getRunnable().run();
                       }else {
                           this.wait(time - curtime);
                       }
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
           }
       });
       thread.start();
    }
}

public class Test2 {
    public static void main(String[] args) {
        Mytimer2 mytimer2 = new Mytimer2();
        mytimer2.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hellow, 3");
            }
        }, 3000);

        mytimer2.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hellow,2");
            }
        },2000);

        mytimer2.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hellow, 1");
            }
        }, 1000);

    }
}
